import TIM from 'tim-wx-sdk-ws'
import TIMUploadPlugin from 'tim-upload-plugin'
import genTestUserSig from '../lib/tim/generate-test-usersig'

class Tim{

  // 模型实例
  static instance = null

  _SDKInstance = null

  _nextReqMessageID = ''

  _messageList = []

  constructor(){

    let options = {
      SDKAppID:1600058630 //APPID 
    };

    let tim = TIM.create(options)

    tim.setLogLevel(0)

    tim.registerPlugin({'tim-upload-plugin':TIMUploadPlugin})

    this._SDKInstance = tim

  }

  static getInstance(){
    if(!Tim.instance){
      Tim.instance = new Tim()
    }
    return Tim.instance
  }

  getSDK(){
    return this._SDKInstance
  }


  // 获取消息列表
  async getMessageList(targetUserId,count = 10){
    if(this.isCompleted){
      return this._messageList
    }
    const res = await this._SDKInstance.getMessageList({
      conversationID:`C2C${targetUserId}`,
      nextReqMessageID:this._nextReqMessageID,
      count: count > 15 ? 15 : count
    })

    this._nextReqMessageID = res.data._nextReqMessageID
    this.isCompleted = res.data.isCompleted
    this._messageList = res.data.messageList

    return this._messageList
  }

  reset(){
    this._nextReqMessageID = ''
    this.isCompleted = false
    this._messageList = []

    return this
  }

  // 登录
  login(){
    // const userInfo = User.getUserInfoByLocal()
    // const textUserSig = genTestUserSig(userInfo.id.toString())
    const textUserSig = genTestUserSig('10086')
    this._SDKInstance.login({
      userID: '10086',
      userSig: textUserSig.userSig
    })

  }

  logout(){
    this._SDKInstance.logout()
  }

  async setMessageRead(targetUserId){
    const res = await this._SDKInstance.setMessageRead({
      conversationID:`C2C${targetUserId}`
    })
    return res.data

  
  }
}

export default Tim